package com.sctvcloud.zhaohua_sd.ui.activities;

import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.ArrayMap;
import android.util.Pair;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.canyinghao.canrefresh.CanRefreshLayout;
import com.gridsum.tracker.GridsumWebDissector;
import com.jiongbull.jlog.JLog;
import com.ruihang.generalibrary.ui.util.OnItemInternalClick;
import com.ruihang.generalibrary.ui.widget.CustomFontEditText;
import com.ruihang.generalibrary.ui.widget.CustomFontTextView;
import com.ruihang.generalibrary.utils.ListUtils;
import com.ruihang.generalibrary.utils.SharedPreferencesUtil;
import com.sctvcloud.zhaohua_sd.R;
import com.sctvcloud.zhaohua_sd.application.Constances;
import com.sctvcloud.zhaohua_sd.base.BaseActivity;
import com.sctvcloud.zhaohua_sd.beans.AFileItem;
import com.sctvcloud.zhaohua_sd.beans.FProgram;
import com.sctvcloud.zhaohua_sd.beans.FSearch;
import com.sctvcloud.zhaohua_sd.beans.LiveItem;
import com.sctvcloud.zhaohua_sd.beans.NewsItem;
import com.sctvcloud.zhaohua_sd.beans.SearchKeyWords;
import com.sctvcloud.zhaohua_sd.beans.SearchResult;
import com.sctvcloud.zhaohua_sd.beans.Titles;
import com.sctvcloud.zhaohua_sd.beans.TopicItem;
import com.sctvcloud.zhaohua_sd.http.AbsNetCallBack;
import com.sctvcloud.zhaohua_sd.http.NetUtils;
import com.sctvcloud.zhaohua_sd.ui.adapter.SearchHistoryAdapter;
import com.sctvcloud.zhaohua_sd.ui.adapter.SearchHotAdapter;
import com.sctvcloud.zhaohua_sd.ui.adapter.SearchResultAdapter;
import com.sctvcloud.zhaohua_sd.ui.util.IListShowData;
import com.sctvcloud.zhaohua_sd.ui.util.RBaseItemDecoration;
import com.sctvcloud.zhaohua_sd.ui.utils.KeyBoardUtils;
import com.sctvcloud.zhaohua_sd.ui.utils.TitleUtils;
import com.sctvcloud.zhaohua_sd.ui.utils.UiListMarginUtils;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class SearchResultMoreActivity extends BaseActivity implements CanRefreshLayout.OnRefreshListener, CanRefreshLayout.OnLoadMoreListener, OnItemInternalClick {
    @BindView(R.id.layout_result)
    protected LinearLayout result_ll;
    @BindView(R.id.search_refresh)
    protected CanRefreshLayout refreshLayout;
    @BindView(R.id.can_content_view)
    protected RecyclerView search_result_list;
    @BindView(R.id.search_result_no_result)
    protected CustomFontTextView no_result;

    public static final String SEARCH_KEY = "search_key";
    private LinearLayoutManager searchResultManager;
    private SearchResultAdapter searchResultAdapter;
    public static final int REQUEST_CODE = 0;
    public static final int RESULT_CODE = 1;
    private int index = 0;
    private int count = 10;
    private String searchKey = "";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        new TitleUtils(this);
        searchKey = getIntent().getStringExtra(SEARCH_KEY);
        initView();
    }

    private void initView() {
        refreshLayout.setOnRefreshListener(this);
        refreshLayout.setOnLoadMoreListener(this);
        searchResultManager = new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false);
        search_result_list.setLayoutManager(searchResultManager);
        search_result_list.addItemDecoration(new RBaseItemDecoration(0));
        search_result_list.setItemAnimator(new DefaultItemAnimator());
        refreshLayout.autoRefresh();
    }

    @Override
    protected void initInject() {
        setContentView(R.layout.activity_search_result_more);
        ButterKnife.bind(this);
    }


    @Override
    public void onLoadMore() {
        if (refreshLayout.isRefreshing()) {
            refreshLayout.loadMoreComplete();
        } else {
            index++;
            searchForPage(searchKey);
        }
    }

    @Override
    public void onRefresh() {
        index = 0;
        refreshLayout.setLoadMoreEnabled(true);
        search(searchKey);
    }

    /**
     * 点击搜索按钮，搜索关键词相关
     *
     * @param keyword
     */
    private void search(String keyword) {
        KeyBoardUtils.closeKeyboard(this);
        ArrayMap<String, Object> param = new ArrayMap<>();
        param.put("keyword", keyword);
        param.put("siteNumber", Constances.SITE_ID);
        param.put("index", index);
        param.put("option", 0);
        param.put("count", count);
        NetUtils.getNetAdapter().keywordOptionSearchFulltext(getOwnerName(), param, new AbsNetCallBack<SearchResult>(SearchResult.class) {
            @Override
            public void onSuc(SearchResult fSearch) {
                if (fSearch != null && (ListUtils.isListValued(fSearch.getAnchorList()) || ListUtils.isListValued(fSearch.getLiveList()) || ListUtils.isListValued(fSearch.getNewsList()) || ListUtils.isListValued(fSearch.getSpecialList()))) {
                    JLog.e("=====search==" + fSearch.toString());
                    no_result.setVisibility(View.GONE);
                    refreshLayout.setVisibility(View.VISIBLE);
                    result_ll.setVisibility(View.VISIBLE);
                    setSearchData(fSearch);
                } else if (index == 0) {
                    result_ll.setVisibility(View.VISIBLE);
                    no_result.setVisibility(View.VISIBLE);
                    refreshLayout.setVisibility(View.GONE);
                }

            }

            @Override
            public void onError(Throwable ex, String errorMsg) {
                super.onError(ex, errorMsg);
                //toast("数据错误");
            }

            @Override
            public void onEnd() {
                super.onEnd();
                onNetFinish();
            }
        });
    }

    /**
     * 查询搜索的更多的结果
     *
     * @param keyword
     */
    private void searchForPage(String keyword) {
        KeyBoardUtils.closeKeyboard(this);
        ArrayMap<String, Object> param = new ArrayMap<>();
        param.put("keyword", keyword);
        param.put("siteNumber", Constances.SITE_ID);
        param.put("index", index);
        param.put("option", 1);
        param.put("count", count);
        NetUtils.getNetAdapter().keywordOptionSearchFulltext(getOwnerName(), param, new AbsNetCallBack<SearchResult>(SearchResult.class) {
            @Override
            public void onSuc(SearchResult fSearch) {
                if (fSearch != null) {
                    JLog.e("=====search==" + fSearch.toString());
                    result_ll.setVisibility(View.VISIBLE);
//                    pageAll=fSearch.getPageAll();
//                    currentPage=fSearch.getPageIndex();
//                    setSeaechData(fSearch);
                    setSearchData(fSearch);
                } else {
                    no_result.setVisibility(View.VISIBLE);
                    refreshLayout.setVisibility(View.GONE);
                }

            }

            @Override
            public void onError(Throwable ex, String errorMsg) {
                super.onError(ex, errorMsg);
                //toast("数据错误");
            }

            @Override
            public void onEnd() {
                super.onEnd();
                onNetFinish();
            }
        });
    }

    private synchronized void onNetFinish() {
        if (refreshLayout.isRefreshing()) {
            refreshLayout.refreshComplete();
        }
        if (refreshLayout.isLoading()) {
            refreshLayout.loadMoreComplete();
        }
    }

    /**
     * 赋值显示搜索结果
     *
     * @param fSearches
     */
    private void setSearchData(SearchResult fSearches) {
        List<NewsItem> newsList = fSearches.getNewsList();
//        List<FProgram> programmeList = fSearches.getProgrammeList();
        List<LiveItem> liveList = fSearches.getLiveList();
        List<AFileItem> anchorList = fSearches.getAnchorList();
        List<TopicItem> specialList = fSearches.getSpecialList();
        List<IListShowData> tempList = new ArrayList<>();
        if (ListUtils.isListValued(anchorList)) {
            AFileItem fileItem = anchorList.get(0);
            if (anchorList.size() > 1) {
                fileItem.setHasMore(true);
            } else {
                fileItem.setHasMore(false);
            }
            tempList.add(fileItem);
        }
        if (ListUtils.isListValued(liveList)) {
            LiveItem liveItem = liveList.get(0);
            if (liveList.size() > 1) {
                liveItem.setHasMore(true);
            } else {
                liveItem.setHasMore(false);
            }
            tempList.add(liveList.get(0));
        }
        if (ListUtils.isListValued(specialList)) {
            if (specialList.size() > 3) {
                for (int i = 0; i < 3; i++) {
                    TopicItem item = specialList.get(i);
                    if (i == 2) {
                        item.setLastItem(true);
                    } else {
                        item.setLastItem(false);
                    }
                    tempList.add(item);
                }
            } else {
                tempList.addAll(specialList);
            }
        }
        if (ListUtils.isListValued(newsList)) {
            if (newsList.size() >= 10) {
                refreshLayout.setLoadMoreEnabled(true);
            } else {
                refreshLayout.setLoadMoreEnabled(false);
            }
            tempList.addAll(newsList);
        } else {
            refreshLayout.setLoadMoreEnabled(false);
        }
//        if (ListUtils.isListValued(newsList)) {
//            tempList.addAll(newsList);
//        }
////        else if (ListUtils.isListValued(programmeList)) {
////            tempList.addAll(programmeList);
////        }
//        else if (ListUtils.isListValued(liveList)) {
//            tempList.addAll(liveList);
//        } else if (ListUtils.isListValued(anchorList)) {
//            tempList.addAll(anchorList);
//        } else if (ListUtils.isListValued(specialList)) {
//            tempList.addAll(specialList);
//        }
//        if (!ListUtils.isListValued(tempList)) {
//            tempList.clear();
//        }
        if (index == 0) {
            if (searchResultAdapter == null) {
                searchResultAdapter = new SearchResultAdapter(this, tempList);
                searchResultAdapter.setOnItemInternalClick(this);
                search_result_list.setAdapter(searchResultAdapter);
            } else {
                searchResultAdapter.setData(tempList);
            }
        } else {
            int pos = searchResultAdapter.getItemCount();
            searchResultAdapter.addDatas(tempList);
            if (pos > 0) {
                searchResultAdapter.notifyItemChanged(pos - 1);
            }
        }
    }




    @Override
    public void onItemInternalClick(View itemView, View view, int position) {
        Intent intent = new Intent(this, MoreSearchActivity.class);
        int type = 0;
        switch (view.getId()) {
            case R.id.rl_more:
                type = 2;
                break;
            case R.id.tv_live_tag_more:
                type = 3;
                break;
            case R.id.tv_tag_more:
                type = 4;
                break;
        }
        if (intent != null) {
            intent.putExtra(BaseActivity.EX_DATA, searchKey);
            intent.putExtra(EX_TYPE, type);
            startActivity(intent);
        }
    }
}

